// 认证相关工具函数

// 获取token
export const getToken = () => {
  return localStorage.getItem('token')
}

// 设置token
export const setToken = (token) => {
  localStorage.setItem('token', token)
}

// 移除token
export const removeToken = () => {
  localStorage.removeItem('token')
}

// 获取用户信息
export const getUserInfo = () => {
  const userInfo = localStorage.getItem('userInfo')
  return userInfo ? JSON.parse(userInfo) : null
}

// 设置用户信息
export const setUserInfo = (userInfo) => {
  localStorage.setItem('userInfo', JSON.stringify(userInfo))
}

// 移除用户信息
export const removeUserInfo = () => {
  localStorage.removeItem('userInfo')
}

// 检查用户是否已登录
export const isAuthenticated = () => {
  const token = getToken()
  return token !== null && token !== undefined && token !== ''
}

// 检查用户角色
export const hasRole = (role) => {
  try {
    const userInfo = getUserInfo()
    // 严格检查userInfo是否存在且为对象
    if (!userInfo || typeof userInfo !== 'object') {
      return false
    }
    
    // 统一使用roles数组格式
    let userRoles = []
    if (userInfo.roles && Array.isArray(userInfo.roles)) {
      userRoles = userInfo.roles
    } else if (userInfo.role) {
      userRoles = Array.isArray(userInfo.role) ? userInfo.role : [userInfo.role]
    }
    
    return userRoles.includes(role)
  } catch (error) {
    console.error('检查用户角色失败:', error)
    return false
  }
}

// 退出登录
export const logout = () => {
  removeToken()
  removeUserInfo()
  // 清除其他可能的用户相关数据
  localStorage.removeItem('permissions')
}

// 获取用户权限
export const getPermissions = () => {
  const permissions = localStorage.getItem('permissions')
  return permissions ? JSON.parse(permissions) : []
}

// 设置用户权限
export const setPermissions = (permissions) => {
  localStorage.setItem('permissions', JSON.stringify(permissions))
}

// 检查用户是否有指定权限
export const hasPermission = (permission) => {
  const permissions = getPermissions()
  return permissions.includes(permission)
}